<template>
  <div v-if="visible" class="modal-overlay" @click="closeModal">
    <div class="modal-content" ref="modalContent" :style="modalStyle" @click.stop="closeAllDropdowns($event)">
      <div class="modal-header" @mousedown.stop="startDragModal">
        <h3>任务块定义配置</h3>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="add-task-section">
        <button class="add-task-btn" @click="addNewTask" :disabled="loading">+ 新建任务块</button>
      </div>
      
      <div class="modal-body">
        <div class="task-table">
          <div class="table-header">
            <div class="header-cell">任务名称</div>
            <div class="header-cell">持续时间(天)</div>
            <div class="header-cell">需要设备</div>
            <div class="header-cell">按天设备配置</div>
            <div class="header-cell">状态</div>
            <div class="header-cell">操作</div>
          </div>
          
          <div v-for="task in tasks" :key="task.id" class="task-row">
            <div class="cell">
              <input 
                v-model="task.name" 
                type="text" 
                placeholder="输入任务名称"
                class="task-input"
                :disabled="loading"
              />
            </div>
            
            <div class="cell">
              <input 
                v-model.number="task.duration" 
                type="number" 
                min="1"
                class="task-input duration-input"
                :disabled="loading"
              />
            </div>
            
            <div class="cell">
              <div class="device-selector" :data-task-id="task.id">
                <!-- 已选设备展示框 -->
                <div class="selected-devices-display" @click.stop="toggleDeviceDropdown(task.id)">
                  <div v-if="task.requiredDevices.length === 0" class="placeholder-text">
                    请选择设备...
                  </div>
                  <div v-else class="selected-devices">
                    <span v-for="device in task.requiredDevices" :key="device" class="device-tag">
                      {{ device }}
                      <button type="button" class="remove-device" @click.stop="removeTaskDevice(task, device)">×</button>
                    </span>
                  </div>
                  <button type="button" class="dropdown-toggle" @click.stop="toggleDeviceDropdown(task.id)">▼</button>
                </div>
                
                <!-- 下拉选择框 -->
                <div v-show="task.showDeviceDropdown" class="device-dropdown" @click.stop>
                  <div class="device-group">
                    <div class="group-title">试验中心</div>
                    <div v-for="device in availableDevices.testCenter" :key="device.id" class="device-option" @click="toggleTaskDeviceSelection(task, device.name)">
                      <input type="checkbox" :checked="task.requiredDevices.includes(device.name)" readonly>
                      <span>{{ device.name }} ({{ device.quantity }}台)</span>
                    </div>
                  </div>
                  <div class="device-group">
                    <div class="group-title">总装&机构展开</div>
                    <div v-for="device in availableDevices.assembly" :key="device.id" class="device-option" @click="toggleTaskDeviceSelection(task, device.name)">
                      <input type="checkbox" :checked="task.requiredDevices.includes(device.name)" readonly>
                      <span>{{ device.name }} ({{ device.quantity }}台)</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="cell">
              <button 
                class="config-btn"
                @click="openDayConfig(task)"
                :disabled="!task.duration || task.duration <= 0 || task.requiredDevices.length === 0"
              >
                配置
              </button>
            </div>
            
            <div class="cell">
              <div class="task-status">
                <span :class="getTaskStatusClass(task)">
                  {{ getTaskStatusText(task) }}
                </span>
              </div>
            </div>
            
            <div class="cell">
              <button class="delete-btn" @click="deleteTask(task.id)" :disabled="loading">删除</button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="cancel-btn" @click="closeModal" :disabled="loading">取消</button>
        <button class="save-btn" @click="saveTasks" :disabled="loading">{{ loading ? '保存中...' : '保存' }}</button>
      </div>
    </div>
    
    <!-- 按天设备配置弹窗 -->
    <div v-if="dayConfigVisible" class="day-config-modal" @click="closeDayConfig">
      <div class="day-config-content" ref="dayConfigContent" :style="dayModalStyle" @click.stop>
        <div class="day-config-header" @mousedown.stop="startDragDayModal">
          <h4>{{ currentTask?.name || '任务' }} - 按天设备配置</h4>
          <div class="header-actions">
            <button class="activate-all-btn" @click="activateAllDays">全部激活</button>
            <button class="close-btn" @click="closeDayConfig">×</button>
          </div>
        </div>
        
        <div class="day-config-body">
          <div v-for="day in currentTask?.duration || 0" :key="day" class="day-config-row">
            <div class="day-label">第{{ day }}天:</div>
            <div class="day-devices-display">
              <!-- 显示已选择的设备 -->
              <div v-if="getDayDevices(day - 1).length > 0" class="selected-day-devices">
                <span 
                  v-for="device in getDayDevices(day - 1)" 
                  :key="device" 
                  class="day-device-tag"
                >
                  {{ device }}
                  <button 
                    type="button" 
                    class="remove-day-device" 
                    @click="removeDayDevice(day - 1, device)"
                  >×</button>
                </span>
              </div>
              <div v-else class="no-device-text">
                暂无设备
              </div>
            </div>
            <button 
              class="activate-day-btn" 
              @click="activateDay(day - 1)"
              :disabled="!currentTask?.requiredDevices || currentTask.requiredDevices.length === 0"
            >
              激活
            </button>
          </div>
        </div>
        
        <div class="day-config-footer">
          <button class="save-btn" @click="saveDayConfig">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'TaskBlockConfiguration',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    availableDevices: {
      type: Object,
      default: () => ({ testCenter: [], assembly: [] })
    }
  },
  
  data() {
    return {
      tasks: [],
      dayConfigVisible: false,
      currentTask: null,
      loading: false,
      // 主弹窗拖拽相关
      isDraggingModal: false,
      modalTop: 0,
      modalLeft: 0,
      dragOffsetModalX: 0,
      dragOffsetModalY: 0,
      // 按天配置弹窗拖拽相关
      isDraggingDayModal: false,
      dayModalTop: 0,
      dayModalLeft: 0,
      dragOffsetDayX: 0,
      dragOffsetDayY: 0
    }
  },
  
  computed: {
    modalStyle() {
      return {
        position: 'fixed',
        top: this.modalTop + 'px',
        left: this.modalLeft + 'px'
      }
    },
    dayModalStyle() {
      return {
        position: 'fixed',
        top: this.dayModalTop + 'px',
        left: this.dayModalLeft + 'px'
      }
    }
  },
  
  methods: {
    // 拖拽主弹窗
    startDragModal(e) {
      const el = this.$refs.modalContent
      if (!el) return
      const rect = el.getBoundingClientRect()
      this.isDraggingModal = true
      this.dragOffsetModalX = e.clientX - rect.left
      this.dragOffsetModalY = e.clientY - rect.top
      window.addEventListener('mousemove', this.onDragModal)
      window.addEventListener('mouseup', this.endDragModal)
    },
    onDragModal(e) {
      if (!this.isDraggingModal) return
      const el = this.$refs.modalContent
      if (!el) return
      const rect = el.getBoundingClientRect()
      const newLeft = e.clientX - this.dragOffsetModalX
      const newTop = e.clientY - this.dragOffsetModalY
      const maxLeft = Math.max(window.innerWidth - rect.width, 0)
      const maxTop = Math.max(window.innerHeight - rect.height, 0)
      this.modalLeft = Math.min(Math.max(newLeft, 0), maxLeft)
      this.modalTop = Math.min(Math.max(newTop, 0), maxTop)
    },
    endDragModal() {
      this.isDraggingModal = false
      window.removeEventListener('mousemove', this.onDragModal)
      window.removeEventListener('mouseup', this.endDragModal)
    },
    centerModal() {
      this.$nextTick(() => {
        const el = this.$refs.modalContent
        if (!el) return
        const rect = el.getBoundingClientRect()
        // 初始位置：水平居中，垂直靠上（例如距顶部20px）
        this.modalLeft = Math.max((window.innerWidth - rect.width) / 2, 0)
        this.modalTop = 20
      })
    },

    // 拖拽按天配置弹窗
    startDragDayModal(e) {
      const el = this.$refs.dayConfigContent
      if (!el) return
      const rect = el.getBoundingClientRect()
      this.isDraggingDayModal = true
      this.dragOffsetDayX = e.clientX - rect.left
      this.dragOffsetDayY = e.clientY - rect.top
      window.addEventListener('mousemove', this.onDragDayModal)
      window.addEventListener('mouseup', this.endDragDayModal)
    },
    onDragDayModal(e) {
      if (!this.isDraggingDayModal) return
      const el = this.$refs.dayConfigContent
      if (!el) return
      const rect = el.getBoundingClientRect()
      const newLeft = e.clientX - this.dragOffsetDayX
      const newTop = e.clientY - this.dragOffsetDayY
      const maxLeft = Math.max(window.innerWidth - rect.width, 0)
      const maxTop = Math.max(window.innerHeight - rect.height, 0)
      this.dayModalLeft = Math.min(Math.max(newLeft, 0), maxLeft)
      this.dayModalTop = Math.min(Math.max(newTop, 0), maxTop)
    },
    endDragDayModal() {
      this.isDraggingDayModal = false
      window.removeEventListener('mousemove', this.onDragDayModal)
      window.removeEventListener('mouseup', this.endDragDayModal)
    },
    centerDayModal() {
      this.$nextTick(() => {
        const el = this.$refs.dayConfigContent
        if (!el) return
        const rect = el.getBoundingClientRect()
        this.dayModalLeft = Math.max((window.innerWidth - rect.width) / 2, 0)
        this.dayModalTop = Math.max((window.innerHeight - rect.height) / 2, 0)
      })
    },

    // API调用方法
    async loadTasks() {
      try {
        this.loading = true
        const response = await axios.get('/api/taskblocks/')
        console.log('任务块API响应:', response.data)
        
        // 检查响应数据结构并正确提取任务块数组
        let tasksData = []
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
          tasksData = response.data.data
        } else if (Array.isArray(response.data)) {
          tasksData = response.data
        } else {
          console.warn('任务块API返回的数据格式不正确:', response.data)
          tasksData = []
        }
        
        this.tasks = tasksData.map(task => {
          const deviceConfig = task.daily_device_config ? this.parseDeviceConfig(task.daily_device_config) : {}
          // 优先使用daily_device_config中的设备列表，如果没有则使用required_device_name
          let requiredDevices = []
          if (deviceConfig.devices && deviceConfig.devices.length > 0) {
            requiredDevices = deviceConfig.devices
          } else if (task.required_device_name) {
            requiredDevices = [task.required_device_name]
          }
          
          return {
            id: task.id,
            name: task.task_name,
            duration: task.duration,
            requiredDevices: requiredDevices,
            dayConfigs: this.ensureArray(deviceConfig.dayConfigs || []),
            showDeviceDropdown: false,
            color: deviceConfig.color || '#87CEEB',
            status: task.status
          }
        })
      } catch (error) {
        console.error('加载任务失败:', error)
        alert('加载任务失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    },

    async saveTaskToAPI(task) {
      const deviceConfig = {
        devices: task.requiredDevices,
        dayConfigs: task.dayConfigs,
        color: task.color
      }
      const taskData = {
        task_name: task.name,
        duration: task.duration,
        required_device: task.requiredDevices.length > 0 ? await this.getDeviceIdByName(task.requiredDevices[0]) : null,
        daily_device_config: JSON.stringify(deviceConfig),
        status: task.status || 'inactive'
      }

      try {
        if (task.id && typeof task.id === 'number' && task.id > 0) {
          // 更新现有任务（只有数字ID且大于0才是真实的任务）
          const response = await axios.put(`/api/taskblocks/${task.id}/`, taskData)
           return response.data
         } else {
           // 创建新任务（包括临时ID的情况）
           const response = await axios.post('/api/taskblocks/', taskData)
          return response.data
        }
      } catch (error) {
        console.error('保存任务失败:', error)
        throw error
      }
    },

    async deleteTaskFromAPI(taskId) {
      try {
        await axios.delete(`/api/taskblocks/${taskId}/`)
      } catch (error) {
        console.error('删除任务失败:', error)
        throw error
      }
    },

    addNewTask() {
      // 为新任务生成一个临时的唯一ID
      const tempId = 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
      const newTask = {
        id: tempId, // 使用临时ID
        name: '',
        duration: 1,
        requiredDevices: [],
        dayConfigs: [],
        showDeviceDropdown: false,
        color: '#87CEEB',
        status: 'inactive'
      }
      this.tasks.push(newTask)
    },
    
    async deleteTask(taskId) {
      if (confirm('确定要删除这个任务块吗？')) {
        try {
          if (taskId && taskId > 0) {
            await this.deleteTaskFromAPI(taskId)
          }
          this.tasks = this.tasks.filter(task => task.id !== taskId)
        } catch (error) {
          alert('删除失败，请重试')
        }
      }
    },

    async getDeviceIdByName(deviceName) {
      try {
        // 直接从后端API获取设备数据
        const response = await axios.get('/api/taskblocks/available_devices/')
        const devices = response.data
        const device = devices.find(d => d.device_name === deviceName)
        return device ? device.id : null
      } catch (error) {
        console.error('获取设备ID失败:', error)
        // 如果API调用失败，回退到本地数据
        const allDevices = [...this.availableDevices.testCenter, ...this.availableDevices.assembly]
        const device = allDevices.find(d => d.name === deviceName || d.device_name === deviceName)
        return device ? device.id : null
      }
    },

    parseDeviceConfig(configStr) {
      try {
        const parsed = JSON.parse(configStr)
        return typeof parsed === 'object' && parsed !== null ? parsed : {}
      } catch (error) {
        console.error('解析设备配置失败:', error)
        return {}
      }
    },

    ensureArray(value) {
      return Array.isArray(value) ? value : []
    },

    toggleDeviceDropdown(taskId) {
      console.log('toggleDeviceDropdown called for task:', taskId)
      const task = this.tasks.find(t => t.id === taskId)
      if (task) {
        task.showDeviceDropdown = !task.showDeviceDropdown
        console.log('Task showDeviceDropdown:', task.showDeviceDropdown)
        // 关闭其他任务的下拉框
        this.tasks.forEach(t => {
          if (t.id !== taskId) {
            t.showDeviceDropdown = false
          }
        })
        
        // 如果打开下拉框，设置位置
        if (task.showDeviceDropdown) {
          this.$nextTick(() => {
            this.positionDropdown(taskId)
          })
        }
      }
    },

    positionDropdown(taskId) {
      const deviceSelector = document.querySelector(`[data-task-id="${taskId}"] .selected-devices-display`)
      const dropdown = document.querySelector(`[data-task-id="${taskId}"] .device-dropdown`)
      
      if (deviceSelector && dropdown) {
        const rect = deviceSelector.getBoundingClientRect()
        dropdown.style.left = rect.left + 'px'
        dropdown.style.top = (rect.bottom + 2) + 'px'
        dropdown.style.width = rect.width + 'px'
      }
    },

    toggleTaskDeviceSelection(task, deviceName) {
      const index = task.requiredDevices.indexOf(deviceName)
      if (index > -1) {
        task.requiredDevices.splice(index, 1)
        
        // 同时从按天设备配置中删除该设备
        if (task.dayConfigs && Array.isArray(task.dayConfigs)) {
          task.dayConfigs.forEach(dayConfig => {
            if (Array.isArray(dayConfig)) {
              const deviceIndex = dayConfig.indexOf(deviceName)
              if (deviceIndex > -1) {
                dayConfig.splice(deviceIndex, 1)
              }
            }
          })
        }
      } else {
        task.requiredDevices.push(deviceName)
      }
    },

    // 获取任务状态文本
    getTaskStatusText(task) {
      if (!task.duration || task.duration <= 0) {
        return '未配置'
      }
      
      if (!task.dayConfigs || task.dayConfigs.length === 0) {
        return '无设备'
      }
      
      // 检查每一天是否都配置了设备
      let hasDeviceDays = 0
      for (let i = 0; i < task.duration; i++) {
        const dayConfig = task.dayConfigs[i]
        if (Array.isArray(dayConfig) && dayConfig.length > 0) {
          hasDeviceDays++
        } else if (typeof dayConfig === 'string' && dayConfig.trim() !== '') {
          hasDeviceDays++
        }
      }
      
      if (hasDeviceDays === 0) {
        return '无设备'
      } else if (hasDeviceDays === task.duration) {
        return '有设备'
      } else {
        return `部分设备(${hasDeviceDays}/${task.duration})`
      }
    },

    // 获取任务状态样式类名
    getTaskStatusClass(task) {
      if (!task.duration || task.duration <= 0) {
        return 'status-unconfigured'
      }
      
      if (!task.dayConfigs || task.dayConfigs.length === 0) {
        return 'status-no-device'
      }
      
      // 检查每一天是否都配置了设备
      let hasDeviceDays = 0
      for (let i = 0; i < task.duration; i++) {
        const dayConfig = task.dayConfigs[i]
        if (Array.isArray(dayConfig) && dayConfig.length > 0) {
          hasDeviceDays++
        } else if (typeof dayConfig === 'string' && dayConfig.trim() !== '') {
          hasDeviceDays++
        }
      }
      
      if (hasDeviceDays === 0) {
        return 'status-no-device'
      } else if (hasDeviceDays === task.duration) {
        return 'status-has-device'
      } else {
        return 'status-partial-device'
      }
    },

    removeTaskDevice(task, deviceName) {
      const index = task.requiredDevices.indexOf(deviceName)
      if (index > -1) {
        task.requiredDevices.splice(index, 1)
        
        // 同时从按天设备配置中删除该设备
        if (task.dayConfigs && Array.isArray(task.dayConfigs)) {
          task.dayConfigs.forEach(dayConfig => {
            if (Array.isArray(dayConfig)) {
              const deviceIndex = dayConfig.indexOf(deviceName)
              if (deviceIndex > -1) {
                dayConfig.splice(deviceIndex, 1)
              }
            }
          })
        }
      }
    },
    
    openDayConfig(task) {
      if (!task.requiredDevices || task.requiredDevices.length === 0) {
        alert('请先选择任务所需的设备')
        return
      }
      
      this.currentTask = task
      // 确保dayConfigs数组长度与持续时间匹配，每个元素都是数组
      if (!task.dayConfigs) {
        task.dayConfigs = []
      }
      while (task.dayConfigs.length < task.duration) {
        task.dayConfigs.push([])
      }
      // 确保现有的每个元素都是数组
      task.dayConfigs = task.dayConfigs.map(dayConfig => 
        Array.isArray(dayConfig) ? dayConfig : (dayConfig ? [dayConfig] : [])
      )
      task.dayConfigs = task.dayConfigs.slice(0, task.duration)
      this.dayConfigVisible = true
    },
    
    closeDayConfig() {
      this.dayConfigVisible = false
      this.currentTask = null
    },
    
    saveDayConfig() {
      // 关闭日配置弹窗
      this.dayConfigVisible = false
      // 在清理前获取当前任务用于广播更新
      const updatedTask = this.currentTask
      this.currentTask = null

      // 广播单个任务块的按天设备配置变更，便于其他组件（如模板配置）实时同步
      if (updatedTask && updatedTask.id) {
        try {
          window.dispatchEvent(new CustomEvent('taskblock-day-config-changed', {
            detail: {
              taskId: updatedTask.id,
              name: updatedTask.name,
              duration: updatedTask.duration,
              requiredDevices: Array.isArray(updatedTask.requiredDevices) ? updatedTask.requiredDevices.slice() : [],
              dayConfigs: Array.isArray(updatedTask.dayConfigs) ? updatedTask.dayConfigs.map(dc => Array.isArray(dc) ? dc.slice() : (dc ? [dc] : [])) : [],
              color: updatedTask.color
            }
          }))
        } catch (e) {
          console.warn('广播日配置变更事件失败:', e)
        }
      }
    },
    
    // 激活指定天的设备（导入需要设备列中的所有设备）
    activateDay(dayIndex) {
      if (!this.currentTask || !this.currentTask.requiredDevices || this.currentTask.requiredDevices.length === 0) {
        alert('请先选择任务所需的设备')
        return
      }
      
      // 将所有需要的设备添加到指定天
      this.currentTask.dayConfigs[dayIndex] = [...this.currentTask.requiredDevices]
      
      console.log(`第${dayIndex + 1}天已激活设备:`, this.currentTask.dayConfigs[dayIndex])
    },
    
    // 激活所有天的设备
    activateAllDays() {
      if (!this.currentTask || !this.currentTask.requiredDevices || this.currentTask.requiredDevices.length === 0) {
        alert('请先选择任务所需的设备')
        return
      }
      
      // 为所有天设置相同的设备列表
      for (let i = 0; i < this.currentTask.duration; i++) {
        this.currentTask.dayConfigs[i] = [...this.currentTask.requiredDevices]
      }
      
      console.log(`已为所有${this.currentTask.duration}天激活设备:`, this.currentTask.requiredDevices)
    },
    
    // 获取指定天的设备列表
    getDayDevices(dayIndex) {
      if (!this.currentTask || !this.currentTask.dayConfigs || !this.currentTask.dayConfigs[dayIndex]) {
        return []
      }
      return Array.isArray(this.currentTask.dayConfigs[dayIndex]) 
        ? this.currentTask.dayConfigs[dayIndex] 
        : []
    },
    
    // 从指定天移除设备
    removeDayDevice(dayIndex, deviceName) {
      if (!this.currentTask || !this.currentTask.dayConfigs[dayIndex]) return
      
      const index = this.currentTask.dayConfigs[dayIndex].indexOf(deviceName)
      if (index > -1) {
        this.currentTask.dayConfigs[dayIndex].splice(index, 1)
      }
    },
    
    async saveTasks() {
      // 验证任务名称不能为空
      const hasEmptyName = this.tasks.some(task => !task.name.trim())
      
      if (hasEmptyName) {
        alert('请填写所有任务的名称')
        return
      }
      
      try {
        this.loading = true
        const savedTasks = []
        
        // 逐个保存任务
        for (let i = 0; i < this.tasks.length; i++) {
          const task = this.tasks[i]
          const processedTask = {
            ...task,
            duration: parseInt(task.duration) || 1
          }
          const savedTask = await this.saveTaskToAPI(processedTask)
          
          // 如果是新任务（临时ID），更新为真实ID
          if (typeof task.id === 'string' && task.id.startsWith('temp_')) {
            this.tasks[i].id = savedTask.id
          }
          
          savedTasks.push(savedTask)
        }
        
        // 向父组件抛出保存事件
        this.$emit('save', { tasks: savedTasks })

        // 广播任务块整体更新事件，供其它组件（如模板配置）同步可用任务块和已排列任务块
        try {
          window.dispatchEvent(new CustomEvent('taskblocks-updated', {
            detail: { tasks: savedTasks }
          }))
        } catch (e) {
          console.warn('广播任务块更新事件失败:', e)
        }

        this.closeModal()
      } catch (error) {
        console.error('保存失败:', error)
        alert('保存失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    closeModal() {
      this.$emit('close')
    },

    // 关闭所有下拉框
    closeAllDropdowns(event) {
      // 如果点击的是设备选择器内部，不关闭下拉框
      if (event && (
        event.target.closest('.device-selector') ||
        event.target.closest('.device-dropdown')
      )) {
        return
      }
      
      this.tasks.forEach(task => {
        task.showDeviceDropdown = false
      })
    },

    // 重新定位所有打开的下拉框
    repositionDropdowns() {
      this.tasks.forEach(task => {
        if (task.showDeviceDropdown) {
          this.positionDropdown(task.id)
        }
      })
    },
    

  },
  
  mounted() {
    // 添加全局点击事件监听器来关闭下拉框
    document.addEventListener('click', this.closeAllDropdowns)
    // 添加滚动和调整大小事件监听器来重新定位下拉框
    window.addEventListener('scroll', this.repositionDropdowns, true)
    window.addEventListener('resize', this.repositionDropdowns)
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadTasks()
        this.$nextTick(() => this.centerModal())
      }
    },
    dayConfigVisible(newVal) {
      if (newVal) {
        this.$nextTick(() => this.centerDayModal())
      }
    }
  },

  beforeDestroy() {
    // 移除全局点击事件监听器
    document.removeEventListener('click', this.closeAllDropdowns)
    window.removeEventListener('scroll', this.repositionDropdowns, true)
    window.removeEventListener('resize', this.repositionDropdowns)
    // 移除拖拽相关监听器
    window.removeEventListener('mousemove', this.onDragModal)
    window.removeEventListener('mouseup', this.endDragModal)
    window.removeEventListener('mousemove', this.onDragDayModal)
    window.removeEventListener('mouseup', this.endDragDayModal)
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 85%;
  max-width: 800px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
  cursor: move;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.add-task-section {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  overflow-x: visible;
  padding: 20px;
  position: relative;
}

.add-task-btn {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.add-task-btn:hover {
  background-color: #218838;
}

.task-table {
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: visible;
}

.table-header {
  display: grid;
  grid-template-columns: 150px 100px 180px 100px 120px 100px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.header-cell {
  padding: 12px 8px;
  font-weight: bold;
  text-align: center;
  border-right: 1px solid #ddd;
  font-size: 14px;
}

.header-cell:last-child {
  border-right: none;
}

.task-row {
  display: grid;
  grid-template-columns: 150px 100px 180px 100px 120px 100px;
  border-bottom: 1px solid #eee;
}

.task-row:last-child {
  border-bottom: none;
}

.cell {
  padding: 8px;
  border-right: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: visible;
}

.cell:last-child {
  border-right: none;
}

.task-input {
  width: 100%;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.duration-input {
  text-align: center;
}

.task-select {
  width: 100%;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}



.config-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.config-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.config-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 设备选择器样式 */
.device-selector {
  width: 100%;
  position: relative;
}

.selected-devices-display {
  display: flex;
  align-items: center;
  min-height: 32px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 4px;
  background: white;
  cursor: pointer;
  font-size: 12px;
}

.placeholder-text {
  color: #999;
  font-style: italic;
  flex: 1;
}

.selected-devices {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  flex: 1;
}

.device-tag {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  padding: 2px 6px;
  background-color: #007bff;
  color: white;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 500;
}

.remove-device {
  background: none;
  border: none;
  color: white;
  font-size: 12px;
  cursor: pointer;
  padding: 0;
  margin-left: 2px;
}

.dropdown-toggle {
  background: none;
  border: none;
  color: #666;
  font-size: 10px;
  cursor: pointer;
  padding: 2px;
  margin-left: 4px;
}

.device-dropdown {
  position: fixed;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 2000;
  max-height: 200px;
  overflow-y: auto;
  min-width: 180px;
}

.device-group {
  border-bottom: 1px solid #eee;
}

.device-group:last-child {
  border-bottom: none;
}

.group-title {
  padding: 8px 12px;
  background: #f8f9fa;
  font-weight: bold;
  font-size: 12px;
  color: #666;
}

.device-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.device-option:hover {
  background-color: #f5f5f5;
}

.device-option input[type="checkbox"] {
  pointer-events: none;
}

.task-preview {
  background-color: #87CEEB !important; /* 浅蓝色 */
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  text-align: center;
  font-size: 12px;
  font-weight: 500;
  min-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 任务状态样式 */
.task-status {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.task-status span {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  min-width: 80px;
}

.status-has-device {
  background-color: #28a745 !important;
  color: white;
}

.status-no-device {
  background-color: #dc3545 !important;
  color: white;
}

.status-partial-device {
  background-color: #ffc107 !important;
  color: #212529;
}

.status-unconfigured {
  background-color: #6c757d !important;
  color: white;
}

.delete-btn {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.delete-btn:hover {
  background-color: #c82333;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 12px 20px;
  border-top: 1px solid #eee;
  background-color: #f8f9fa;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #545b62;
}

.save-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #0056b3;
}

/* 按天配置弹窗样式 */
.day-config-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1100;
}

.day-config-content {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-height: 70vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.day-config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
  cursor: move;
}

.day-config-header h4 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.activate-all-btn {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
}

.activate-all-btn:hover {
  background-color: #218838;
}

.day-config-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.day-config-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 15px;
}

.day-label {
  width: 80px;
  font-weight: bold;
  color: #333;
}

.day-device-select {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.day-devices-display {
  flex: 1;
  display: flex;
  align-items: center;
  min-height: 40px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.selected-day-devices {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  width: 100%;
}

.no-device-text {
  color: #999;
  font-style: italic;
  font-size: 14px;
}

.day-device-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background-color: #007bff;
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.remove-day-device {
  background: none;
  border: none;
  color: white;
  font-size: 14px;
  cursor: pointer;
  padding: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.remove-day-device:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.activate-day-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  min-width: 60px;
}

.activate-day-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.activate-day-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.day-config-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  background-color: #f8f9fa;
}
</style>